<template>
  <el-card>
    <el-form ref="form"
             class="form-box"
             label-width="120px"
             label-position="right"
             size="small"
             :model="form"
             :rules="rules">
      <el-form-item label="账号"
                    :prop="form.userId ? '' : 'userAccount'"
                    style="margin-bottom: 18px">
        <div v-if="!form.userId">
          <el-input v-model.trim="form.userAccount"
                    placeholder
                    maxlength="20"
                    minlength="5"
                    @input="checkName(form.userAccount, tenantAlias)">
            <span slot="suffix">@{{ tenantAlias }}</span>
          </el-input>
          <span>账号只能为纯英文或者英文开头+数字组合，5-20个字符</span>
        </div>
        <span v-else> {{ form.userAccount }}@{{ tenantAlias }} </span>
      </el-form-item>
      <el-form-item v-if="!form.userId"
                    label="密码"
                    prop="password"
                    class="el-amsitem"
                    style="margin-bottom: 18px">
        <el-input v-model.trim="form.password"
                  minlength="6"
                  maxlength="20"
                  type="password"
                  show-password
                  @input="onInput(form.password)"
                  @blur="loseBlur"></el-input>
        <password-intensity :is-feeble="isFeeble"
                            :is-middle="isMiddle"
                            :is-strong="isStrong"></password-intensity>
      </el-form-item>
      <el-form-item v-if="!form.userId"
                    label="确认密码"
                    prop="confirmPassword"
                    class="el-amsitem">
        <el-input v-model.trim="form.confirmPassword"
                  minlength="6"
                  maxlength="20"
                  type="password"
                  show-password
                  @input="newOnInput(form.confirmPassword)"
                  @blur="newLoseBlur"></el-input>
        <password-intensity :is-feeble="isNewFeeble"
                            :is-middle="isNewMiddle"
                            :is-strong="isNewStrong"></password-intensity>
      </el-form-item>
      <el-form-item v-if="form.type !== 1"
                    label="角色"
                    prop="roles"
                    class="characterBox">
        <role-group v-model="form.roles" />
      </el-form-item>
      <el-form-item label="昵称"
                    prop="name"
                    style="margin-bottom: 8px">
        <el-input v-model.trim="form.name"
                  placeholder
                  maxlength="20">
        </el-input>
      </el-form-item>
      <el-form-item style="margin-top: 18px"
                    label="">
        <el-button @click="save">保存</el-button>
        <el-button @click="reset">重置</el-button>
        <el-button @click="$router.back()">返回</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>
<script>
import PasswordIntensity from "@/components/public/PasswordIntensity";
import { regExpConfig } from "@/libs/regular.js";
import RoleGroup from "@/components/advance/roleGroup/RoleGroup.vue";
import { user, tenant } from "@/api/index";
import { ValidateRules } from "@/libs/util";
export default {
  name: "AddUser",
  components: { PasswordIntensity, RoleGroup },
  data () {
    return {
      form: {
        userId: null,
        userAccount: "",
        password: "",
        confirmPassword: "",
        roles: [],
        name: ""
      },
      rules: {
        userAccount: [ValidateRules.required],
        password: [
          ValidateRules.required
          //  {
          //   pattern: /^(\d{0,7})(\.(\d{0,2}))?$/g,
          //   message: "最多可输入7位整数，2位小数",
          //   trigger: "change",
          // },
        ],
        confirmPassword: [ValidateRules.required],
        roles: [ValidateRules.required],
        name: [ValidateRules.required]
      },
      userAccountCopy: null,
      // password 强度
      isFeeble: false,
      isMiddle: false,
      isStrong: false,
      isNewFeeble: false,
      isNewMiddle: false,
      isNewStrong: false,
      userInfo: sessionStorage.getItem('userInfo')
    };
  },
  computed: {
    user () {
      return JSON.parse(this.userInfo)
    },
    tenantAlias () {
      return this.user?.tenantAlias
    }
  },
  mounted () {
    // 判断 是否 编辑 用 {{this.$route.query}} --> 需要传到编辑接口的参数
    if (this.$route.query.userId) {
      // 调用编辑方法
      this.getDetail();
    }
  },
  methods: {
    async checkName (val, name) {
      if (!val) return;
      if (val) {
        let reg = /^[a-zA-Z][a-zA-Z0-9_]*$/;
        if (reg.test(val)) {
          let endName = `${val}@${name}`;
          this.userAccountCopy = val;
          let { data } = await user.checkName(endName);
          if (data) {
            this.$message.error("账号名称已存在，请更换其他");
            this.form.userAccount = this.userAccountCopy = "";
          }
        } else {
          this.form.userAccount = this.userAccountCopy;
        }
      } else {
        return;
      }
    },
    async getDetail () {
      let { data, code } = await user.getUserInfo(this.$route.query.userId);
      if (code === 0) this.form = data;
    },
    reset () {
      this.$refs.form.resetFields();
    },
    save () {
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (!this.$route.query.userId) {
            if (this.form.password !== this.form.confirmPassword) {
              this.$message({
                message: "两次密码输入不一致",
                type: "warning"
              });
            } else if (
              this.form.userAccount.length < 5 ||
              this.form.userAccount.length > 20
            ) {
              this.$message({
                message: "账号长度5-20位",
                type: "warning"
              });
            } else if (
              this.form.password.length < 6 ||
              this.form.password.length > 20
            ) {
              this.$message({
                message: "密码长度6-20位",
                type: "warning"
              });
            } else if (this.isFeeble || this.isNewFeeble) {
              this.$message({
                message:
                  "密码强度不够，至少要包含数字，字母，特殊字符三项中两项！",
                type: "warning"
              });
            } else {
              this.insert();
            }
          } else {
            this.insert();
          }
        }
      });
    },
    async insert () {
      let formData = JSON.parse(JSON.stringify(this.form));
      if (!this.$route.query.userId) {
        formData.password = this.$md5(formData.password);
        formData.confirmPassword = this.$md5(formData.confirmPassword);
      }
      let { code, message } = await tenant[
        this.$route.query.userId ? "updateUser" : "addUser"
      ](formData, this.$route.query.userId ? this.$route.query.userId : "");

      this.$message[code === 0 ? "success" : "error"](message);
      if (code === 0) {
        this.$router.go(-1);
      }
    },
    // 输入新密码input的事件
    onInput (value) {
      if (!value) {
        this.isMiddle = false;
        this.isFeeble = false;
        this.isStrong = false;
        return;
      }
      if (regExpConfig.strongContent.test(value)) {
        this.isMiddle = false;
        this.isFeeble = false;
        this.isStrong = true;
      } else if (regExpConfig.middleSpecial.test(value)) {
        this.isFeeble = false;
        this.isStrong = false;
        this.isMiddle = true;
      } else {
        this.isStrong = false;
        this.isMiddle = false;
        this.isFeeble = true;
      }
    },
    // 确认新密码input的事件
    newOnInput (value) {
      if (!value) {
        this.isNewMiddle = false;
        this.isNewFeeble = false;
        this.isNewStrong = false;
        return;
      }
      if (regExpConfig.strongContent.test(value)) {
        this.isNewMiddle = false;
        this.isNewFeeble = false;
        this.isNewStrong = true;
      } else if (regExpConfig.middleSpecial.test(value)) {
        this.isNewFeeble = false;
        this.isNewStrong = false;
        this.isNewMiddle = true;
      } else {
        this.isNewStrong = false;
        this.isNewMiddle = false;
        this.isNewFeeble = true;
      }
    },
    // 确认新密码失去焦点时
    newLoseBlur () {
      if (this.isNewFeeble) {
        this.$message({
          message: "密码强度不够，至少要包含数字，字母，特殊字符三项中两项！",
          type: "warning"
        });
      }
    },
    // 输入新密码失去焦点时
    loseBlur () {
      if (this.isFeeble) {
        this.$message({
          message: "密码强度不够，至少要包含数字，字母，特殊字符三项中两项！",
          type: "warning"
        });
      }
    }
  }
};
</script>
<style scoped>
.form-box {
  width: 900px;
  min-width: 900px;
}
</style>
